#include "connecteh.h"
#include "common.h"
#include "event.h"
#include "reactor.h"
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <unistd.h>

event_handler_t *create_connecteh(int connfd, reactor_t *reactor)
{
	event_handler_t *eh;
	eh = (event_handler_t *)malloc(sizeof(event_handler_t));
	if (eh == NULL)
	{
		outputError(errno, "%s", "malloc event_handler_t");
	}
	eh->fd = connfd;
	eh->handle_event = handle_event;
	eh->reactor = reactor;

	return eh;
}

static void *handle_event(void *msg)
{
	handle_event_msg_t *arg;
	int fd, readN;
	char buf[BUF_SIZE];

	arg = (handle_event_msg_t *)msg;
	fd = arg->fd;

	if (arg->events & EPOLLRDHUP)
	{
		close(fd);
	}
	else
	{
		while ((readN = read(fd, buf, BUF_SIZE)) > 0)
		{
			if (write(fd, buf, readN) != readN)
			{
				outputError(errno, "%s", "write error");
			}
		}
	}
}
